package com.dcits.mvc.common.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.dcits.business.userconfig.UserCommonConfig;
import com.dcits.business.userconfig.UserSpace;
import com.dcits.dto.DTOParseUtil;
import com.dcits.mvc.base.BaseController;
import com.dcits.mvc.common.model.UserConfig;
import com.dcits.mvc.common.service.UserConfigService;
import com.dcits.tool.StringUtils;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;

public class UserConfigController extends BaseController {
	
	private static UserConfigService service = new UserConfigService();
	
	@ActionKey("/")
	@Clear
	public void index() {
		render("/login.html");
	}
	
	public void login() {
		UserConfig config = service.findByKey(getPara("userKey"));
		UserSpace space = UserSpace.getUserSpace(config.getUserKey());
		if (space == null) {
			//初始化用户空间
			UserSpace.addUserSpace(config);
		}
		renderSuccess(config, "success");
	}
	
	public void add () {
		String userKey = getPara("userKey");		
		service.save(userKey);
		renderSuccess(null, "添加成功!");
	}
	
	public void del() {
		service.delbyKey(getPara("userKey"));
		renderSuccess(null, "删除成功!");
	}
	
	public void getUserSetting() {
		UserConfig config = service.findByKey(getPara("userKey"));
		renderSuccess(config.parseUserSetting(), "success");		
	}
	
	public void listSpace() {
		renderSuccess(DTOParseUtil.parseUserSpace(), "");
	}
	
	@SuppressWarnings("unchecked")
	public void updateSetting() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		String setting = getPara("setting");
		String userKey = getPara("userKey");
		UserSpace space = UserSpace.getUserSpace(userKey);
		JSONObject settingObj = JSONObject.parseObject(setting);
		
		UserCommonConfig config = space.getUserConfig().parseUserSetting();
		
		String type = settingObj.getString("type");
		Map<String, Object> typeSetting = (Map<String, Object>) UserCommonConfig.class
				.getMethod("get" + StringUtils.toUpperCaseFirstOne(type)).invoke(config);
		if ("alert".equals(type)) {
			typeSetting = (Map<String, Object>) typeSetting.get(settingObj.getString("serverType"));
		}
		
		for (String key:typeSetting.keySet()) {
			if (settingObj.get(key) != null) {
				typeSetting.put(key, settingObj.get(key));
			}
		}
		
		service.updateSetting(userKey, JSONObject.toJSONString(config));
		space.getUserConfig().setConfigInfoJson(JSONObject.toJSONString(config));
		
		renderSuccess(null, "更新成功");
	}
}
